<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API Key申请系统</title>
    <!-- Element Plus CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus@2.4.4/dist/index.css" crossorigin="anonymous">
    <!-- FingerprintJS -->
    <script src="https://cdn.jsdelivr.net/npm/@fingerprintjs/fingerprintjs@4.2.1/dist/fp.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .app-container {
            min-height: 100vh;
            padding: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .main-card {
            background: white;
            border-radius: 16px;
            padding: 40px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 600px;
        }

        .header-section {
            text-align: center;
            margin-bottom: 40px;
        }

        .header-title {
            font-size: 32px;
            font-weight: 700;
            color: #303133;
            margin: 0 0 12px 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .header-subtitle {
            font-size: 16px;
            color: #909399;
            margin: 0;
        }

        .tab-section {
            margin-bottom: 30px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .form-title {
            font-size: 20px;
            font-weight: 600;
            color: #303133;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .form-icon {
            width: 24px;
            height: 24px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 12px;
        }

        .el-form-item {
            margin-bottom: 24px;
        }

        .el-input, .el-textarea {
            border-radius: 8px;
        }

        .submit-button {
            width: 100%;
            height: 48px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
        }

        .query-result {
            margin-top: 20px;
            padding: 16px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .application-card {
            background: white;
            border-radius: 6px;
            margin-bottom: 12px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .application-card:last-child {
            margin-bottom: 0;
        }

        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 8px 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-title {
            font-weight: 600;
            font-size: 14px;
        }

        .card-status {
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: 600;
            background: rgba(255, 255, 255, 0.2);
        }

        .card-content {
            padding: 10px 12px;
        }

        .result-item {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 6px;
            padding: 3px 0;
            border-bottom: 1px solid #f0f0f0;
            line-height: 1.4;
        }

        .result-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }

        .result-label {
            font-weight: 500;
            color: #606266;
            font-size: 13px;
            min-width: 70px;
            flex-shrink: 0;
        }

        .result-value {
            color: #303133;
            font-size: 13px;
            text-align: right;
            word-break: break-all;
        }

        .status-pending {
            color: #e6a23c;
        }

        .status-approved {
            color: #67c23a;
        }

        .status-rejected {
            color: #f56c6c;
        }

        .fingerprint-info {
            background: #f0f9ff;
            border: 1px solid #bfdbfe;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 20px;
            font-size: 14px;
            color: #1e40af;
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
        }

        .loading-content {
            background: white;
            padding: 30px;
            border-radius: 8px;
            text-align: center;
        }

        @media (max-width: 768px) {
            .app-container {
                padding: 10px;
            }

            .main-card {
                padding: 20px;
            }

            .header-title {
                font-size: 24px;
            }
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="app-container">
            <div class="main-card">
                <!-- 头部 -->
                <div class="header-section">
                    <h1 class="header-title">API Key申请系统</h1>
                    <p class="header-subtitle">申请您的专属API密钥，开启开发之旅</p>
                </div>

                <!-- 标签页 -->
                <div class="tab-section">
                    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                        <el-tab-pane label="申请API Key" name="apply">
                            <div class="form-section">
                                <div class="form-title">
                                    <div class="form-icon">📝</div>
                                    填写申请信息
                                </div>

                                <!-- 指纹信息提示 -->
                                <div class="fingerprint-info" v-if="fingerprint">
                                    <strong>🔒 安全提示：</strong> 系统已自动获取您的浏览器指纹用于身份验证，无需手动输入。
                                </div>

                                <el-form :model="applyForm" :rules="applyRules" ref="applyFormRef" label-width="120px">
                                    <el-form-item label="手机号码" prop="phoneNumber">
                                        <el-input 
                                            v-model="applyForm.phoneNumber" 
                                            placeholder="请输入您的手机号码"
                                            maxlength="11"
                                            show-word-limit>
                                        </el-input>
                                    </el-form-item>

                                    <el-form-item label="验证密码" prop="verifyPassword">
                                        <el-input 
                                            v-model="applyForm.verifyPassword" 
                                            type="password" 
                                            placeholder="请设置一个验证密码，用于后续查询（可选）"
                                            maxlength="20"
                                            show-word-limit
                                            show-password>
                                        </el-input>
                                        <div class="form-tip">
                                            🔐 建议设置验证密码，否则可能存在信息泄露风险
                                        </div>
                                    </el-form-item>

                                    <el-form-item label="申请说明" prop="remark">
                                        <el-input 
                                            v-model="applyForm.remark" 
                                            type="textarea" 
                                            :rows="4"
                                            placeholder="请简要说明您申请API Key的用途（可选）"
                                            maxlength="500"
                                            show-word-limit>
                                        </el-input>
                                    </el-form-item>

                                    <el-form-item>
                                        <el-button 
                                            type="primary" 
                                            class="submit-button"
                                            @click="submitApplication"
                                            :loading="submitting">
                                            {{ submitting ? '提交中...' : '提交申请' }}
                                        </el-button>
                                    </el-form-item>
                                </el-form>
                            </div>
                        </el-tab-pane>

                        <el-tab-pane label="查询申请状态" name="query">
                            <div class="form-section">
                                <div class="form-title">
                                    <div class="form-icon">🔍</div>
                                    查询申请状态
                                </div>

                                <el-form :model="queryForm" :rules="queryRules" ref="queryFormRef" label-width="120px">
                                    <el-form-item label="手机号码" prop="phoneNumber">
                                        <el-input 
                                            v-model="queryForm.phoneNumber" 
                                            placeholder="请输入申请时的手机号码"
                                            maxlength="11">
                                        </el-input>
                                    </el-form-item>

                                    <el-form-item label="验证密码" prop="verifyPassword">
                                        <el-input 
                                            v-model="queryForm.verifyPassword" 
                                            type="password" 
                                            placeholder="请输入申请时设置的验证密码（可选）"
                                            show-password>
                                        </el-input>
                                        <div class="form-tip">
                                            💡 如果未设置验证密码，系统将使用浏览器指纹进行查询
                                        </div>
                                    </el-form-item>

                                    <el-form-item>
                                        <el-button 
                                            type="primary" 
                                            class="submit-button"
                                            @click="queryApplication"
                                            :loading="querying">
                                            {{ querying ? '查询中...' : '查询申请' }}
                                        </el-button>
                                    </el-form-item>
                                </el-form>

                                <!-- 查询结果 -->
                                <div v-if="queryResult && queryResult.length > 0" class="query-result">
                                    <h3 style="margin-top: 0; color: #303133;">申请记录列表 ({{ queryResult.length }} 条)</h3>
                                    
                                    <div v-for="(application, index) in queryResult" :key="application.id" class="application-card">
                                        <div class="card-header">
                                            <span class="card-title">{{ application.name || `申请 #${application.id}` }}</span>
                                            <span class="card-status" :class="getStatusClass(application.status)">
                                                {{ getStatusText(application.status) }}
                                            </span>
                                        </div>
                                        
                                        <div class="card-content">
                                            <div class="result-item">
                                                <span class="result-label">手机号码：</span>
                                                <span class="result-value">{{ application.phoneNumber }}</span>
                                            </div>
                                            <div class="result-item">
                                                <span class="result-label">申请时间：</span>
                                                <span class="result-value">{{ formatDate(application.applyTime) }}</span>
                                            </div>
                                            <div v-if="application.description" class="result-item">
                                                <span class="result-label">申请说明：</span>
                                                <span class="result-value">{{ application.description }}</span>
                                            </div>
                                            <div v-if="application.reviewTime" class="result-item">
                                                <span class="result-label">审核时间：</span>
                                                <span class="result-value">{{ formatDate(application.reviewTime) }}</span>
                                            </div>
                                            <div v-if="application.reviewer" class="result-item">
                                                <span class="result-label">审核人：</span>
                                                <span class="result-value">{{ application.reviewer }}</span>
                                            </div>
                                            <div v-if="application.status === 'APPROVED' && application.apiKey && application.apiKey !== '已生成'" class="result-item">
                                                <span class="result-label">API Key：</span>
                                                <span class="result-value" style="font-family: monospace; background: #f5f5f5; padding: 4px 8px; border-radius: 4px;">
                                                    {{ application.apiKey }}
                                                </span>
                                            </div>
                                            <div v-else-if="application.status === 'APPROVED' && application.apiKey === '已生成'" class="result-item">
                                                <span class="result-label">API Key：</span>
                                                <span class="result-value" style="color: #67c23a;">已生成，请联系管理员获取</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </div>
        </div>

        <!-- 加载遮罩 -->
        <div v-if="loading" class="loading-overlay">
            <div class="loading-content">
                <el-icon class="is-loading" style="font-size: 24px; margin-bottom: 12px;">
                    <Loading />
                </el-icon>
                <div>正在初始化浏览器指纹...</div>
            </div>
        </div>
    </div>

    <!-- Vue 3 -->
    <script src="https://unpkg.com/vue@3.3.8/dist/vue.global.js"></script>
    <!-- Element Plus -->
    <script src="https://unpkg.com/element-plus@2.4.4/dist/index.full.js"></script>
    <!-- Element Plus Icons -->
    <script src="https://unpkg.com/@element-plus/icons-vue@2.1.0/dist/index.iife.min.js"></script>

    <script>
        const { createApp, ref, reactive, onMounted } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;

        createApp({
            setup() {
                // 响应式数据
                const loading = ref(true);
                const activeTab = ref('apply');
                const submitting = ref(false);
                const querying = ref(false);
                const fingerprint = ref('');
                const queryResult = ref(null);
                const applyFormRef = ref(null);
                const queryFormRef = ref(null);

                // 申请表单
                const applyForm = reactive({
                    phoneNumber: '',
                    verifyPassword: '',
                    remark: ''
                });

                // 查询表单
                const queryForm = reactive({
                    phoneNumber: '',
                    verifyPassword: ''
                });

                // 表单验证规则
                const applyRules = {
                    phoneNumber: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
                    ]
                };

                const queryRules = {
                    phoneNumber: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
                    ]
                };

                // 初始化浏览器指纹
                const initFingerprint = async () => {
                    try {
                        const fp = await FingerprintJS.load();
                        const result = await fp.get();
                        fingerprint.value = result.visitorId;
                        console.log('Browser fingerprint:', fingerprint.value);
                    } catch (error) {
                        console.error('Failed to get fingerprint:', error);
                        ElMessage.error('获取浏览器指纹失败，请刷新页面重试');
                    } finally {
                        loading.value = false;
                    }
                };

                // 提交申请
                const submitApplication = async () => {
                    if (!applyFormRef.value) return;

                    try {
                        await applyFormRef.value.validate();
                        
                        if (!fingerprint.value) {
                            ElMessage.error('浏览器指纹获取失败，请刷新页面重试');
                            return;
                        }

                        submitting.value = true;

                        const response = await fetch('/api/applications/submit', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                phoneNumber: applyForm.phoneNumber,
                                verifyPassword: applyForm.verifyPassword,
                                fingerprint: fingerprint.value,
                                remark: applyForm.remark
                            })
                        });

                        const result = await response.json();

                        if (response.ok && result.success) {
                            ElMessage.success('申请提交成功！请等待管理员审核。');
                            // 重置表单
                            applyFormRef.value.resetFields();
                            // 切换到查询标签页
                            activeTab.value = 'query';
                            queryForm.phoneNumber = applyForm.phoneNumber;
                        } else {
                            ElMessage.error(result.message || '申请提交失败');
                        }
                    } catch (error) {
                        console.error('Submit error:', error);
                        ElMessage.error('网络错误，请稍后重试');
                    } finally {
                        submitting.value = false;
                    }
                };

                // 查询申请
                const queryApplication = async () => {
                    if (!queryFormRef.value) return;

                    try {
                        await queryFormRef.value.validate();

                        querying.value = true;
                        queryResult.value = null;

                        let url = '';
                        let body = {};

                        // 根据验证密码是否为空自动判断查询方式
                        if (queryForm.verifyPassword && queryForm.verifyPassword.trim()) {
                            // 有验证密码，使用手机号+验证密码查询
                            url = '/api/applications/query/phone';
                            body = {
                                phoneNumber: queryForm.phoneNumber,
                                verifyPassword: queryForm.verifyPassword
                            };
                        } else {
                            // 没有验证密码，使用手机号查询该手机号下的所有申请
                            url = '/api/applications/query/phone';
                            body = {
                                phoneNumber: queryForm.phoneNumber
                            };
                        }

                        const response = await fetch(url, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(body)
                        });

                        const result = await response.json();

                        if (response.ok && result.success) {
                            // 现在后端统一返回数组格式
                            if (Array.isArray(result.data)) {
                                queryResult.value = result.data;
                                if (result.data.length === 0) {
                                    ElMessage.warning('未找到相关申请记录');
                                    return;
                                }
                            } else {
                                // 兼容单个记录的情况，转换为数组
                                queryResult.value = [result.data];
                            }
                            ElMessage.success(`查询成功，找到 ${queryResult.value.length} 条申请记录`);
                        } else {
                            ElMessage.error(result.message || '查询失败');
                        }
                    } catch (error) {
                        console.error('Query error:', error);
                        ElMessage.error('网络错误，请稍后重试');
                    } finally {
                        querying.value = false;
                    }
                };

                // 标签页切换
                const handleTabClick = (tab) => {
                    queryResult.value = null;
                };

                // 获取状态样式类
                const getStatusClass = (status) => {
                    switch (status) {
                        case 'PENDING':
                            return 'status-pending';
                        case 'APPROVED':
                            return 'status-approved';
                        case 'REJECTED':
                            return 'status-rejected';
                        default:
                            return '';
                    }
                };

                // 获取状态文本
                const getStatusText = (status) => {
                    switch (status) {
                        case 'PENDING':
                            return '待审核';
                        case 'APPROVED':
                            return '已通过';
                        case 'REJECTED':
                            return '已拒绝';
                        default:
                            return '未知状态';
                    }
                };

                // 格式化日期
                const formatDate = (dateString) => {
                    if (!dateString) return '';
                    const date = new Date(dateString);
                    return date.toLocaleString('zh-CN');
                };

                // 组件挂载时初始化
                onMounted(() => {
                    initFingerprint();
                });

                return {
                    loading,
                    activeTab,
                    submitting,
                    querying,
                    fingerprint,
                    queryResult,
                    applyForm,
                    queryForm,
                    applyRules,
                    queryRules,
                    applyFormRef,
                    queryFormRef,
                    submitApplication,
                    queryApplication,
                    handleTabClick,
                    getStatusClass,
                    getStatusText,
                    formatDate
                };
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>